//
//  VKVoucherChildController.m
//  V-Learn
//
//  Created by liubo on 2019/1/10.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKVoucherChildController.h"
#import "VKVoucherChildYICell.h"
#import "VKVoucherChildWeiCell.h"
#import "VKVoucherChildGuoCell.h"

@interface VKVoucherChildController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;
@property (nonatomic, assign) BOOL isAllSelect;
@property (nonatomic, assign) NSInteger yincang;

@end

@implementation VKVoucherChildController

- (instancetype)initWithId:(NSInteger)scrollId
{
    self = [super init];
    if (self) {
        self.scrollId = scrollId;
    }
    return self;
}

-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT - 40) style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        _tableView.backgroundColor = [UIColor cz_colorWithRed:244 green:244 blue:244];
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = @[];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self tableView];
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(voucherButton:) name:[NSString stringWithFormat:@"ManagerY%ld",self.scrollId] object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(voucherButton:) name:[NSString stringWithFormat:@"ManagerY"] object:nil];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    [self setupLeftRefresh];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteButton:) name:@"ManagerDelete" object:nil];

}
- (void)deleteButton:(NSNotification *)no{

    NSMutableArray *idArray = [[NSMutableArray alloc]init];
    NSMutableArray *modelArray = [[NSMutableArray alloc]init];
    NSMutableArray *deleteArray = [[NSMutableArray alloc]init];
    for (VKVoucherChildModel *model in self.dataArray) {
        if (model.isSelectRow == YES) {
            [idArray addObject:@([model.voucherId intValue])];
            [deleteArray addObject:model];
        }else{
            [modelArray addObject:model];
        }
    }
    
    NSString *flags = [idArray componentsJoinedByString:@","];
    NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token,@"voucherIds":flags}.mutableCopy;
    [WYHXNetWorkService netWorkSerViceRequestWithPostUrl:WKMeDeleteVoucher withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
        
        if ([result[@"code"]integerValue] == 200) {
            
//            [self.dataArray removeAllObjects];
//            [self.dataArray removeObjectsInArray:modelArray];
            [self.dataArray removeObjectsInArray:deleteArray];
            
            [MBProgressHUD showSuccess:@"删除成功" toView:self.view];
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [self.tableView reloadData];
    }];
}
//刷新
- (void)setupLeftRefresh
{   //下拉
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];
    
    [self.tableView.mj_header beginRefreshing];
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
    [self setupLoadFirstData];
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{
    
    ++(_page);
    _pageNums = 10;
    [self setupLoadFirstData];
}//决定footer的状态
- (void)checkFooterState{
    
    [self.tableView.mj_footer endRefreshingWithNoMoreData];
}

- (void)setupLoadFirstData{
    VKWeakSelf(self)
    NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token,@"state":@(self.scrollId),@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKMeVoucher withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
        
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.dataArray removeAllObjects];
            }
            
            for (NSDictionary *dic in result[@"data"]) {
                VKVoucherChildModel *model = [VKVoucherChildModel mj_objectWithKeyValues:dic];
                model.isAllSelect = self.isAllSelect;
                model.isSelect = self.isAllSelect;
                [self.dataArray addObject:model];
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.tableView.mj_footer endRefreshing];
            }
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.tableView reloadData];
        
        [self.tableView.mj_header endRefreshing];
    }];
    
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (void)voucherButton:(NSNotification *)no{
//    NSLog(@"ManagerHidden:%@",no.object[@"ManagerHidden"]);
//    NSLog(@"scrollId:%ld",self.scrollId);
//    NSLog(@"dataArray:%ld",self.dataArray.count);
    self.yincang = [no.object[@"ManagerHidden"] integerValue];
    if ([no.object[@"ManagerHidden"] integerValue] == 1) { // 隐藏
        self.tableView.frame = CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT - 40);
        for (int i = 0; i < self.dataArray.count; i++) {
            VKVoucherChildModel *model = self.dataArray[i];
            model.isSelect = NO;
            model.isAllSelect = NO;
            [self.dataArray replaceObjectAtIndex:i withObject:model];
        }
        self.isAllSelect = NO;
        [self.tableView reloadData];

    }else{// 显示
        self.tableView.frame = CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT - 40 - 50);
        for (int i = 0; i < self.dataArray.count; i++) {
            VKVoucherChildModel *model = self.dataArray[i];
            model.isSelect = YES;
            model.isAllSelect = YES;

            [self.dataArray replaceObjectAtIndex:i withObject:model];
        }
        self.isAllSelect = YES;
        [self.tableView reloadData];

    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return 180;
    }
    return 165;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.scrollId == 1) {// 未使用
        VKVoucherChildWeiCell *cell = [VKVoucherChildWeiCell cellWithTableView:tableView withIndexPath:indexPath withModel:self.dataArray[indexPath.row]];
        VKVoucherChildModel *model = self.dataArray[indexPath.row];
        cell.deleteBtn.tag = indexPath.row + 10000;
        [cell.deleteBtn addTarget:self action:@selector(weiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        model.row = indexPath.row;
        cell.model = model;
        return cell;
    }else if (self.scrollId == 2){// 已使用
        VKVoucherChildYICell *cell = [VKVoucherChildYICell cellWithTableView:tableView withIndexPath:indexPath withModel:self.dataArray[indexPath.row]];
        VKVoucherChildModel *model = self.dataArray[indexPath.row];
        model.row = indexPath.row;
        cell.model = model;
        cell.deleteBtn.tag = indexPath.row + 10000;
        [cell.deleteBtn addTarget:self action:@selector(weiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else if (self.scrollId == 3){// 已过期
        VKVoucherChildGuoCell *cell = [VKVoucherChildGuoCell cellWithTableView:tableView withIndexPath:indexPath withModel:self.dataArray[indexPath.row]];
        VKVoucherChildModel *model = self.dataArray[indexPath.row];
        model.row = indexPath.row;
        cell.model = model;
        cell.deleteBtn.tag = indexPath.row + 10000;
        [cell.deleteBtn addTarget:self action:@selector(weiBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
    
    return nil;
}

// 未使用的
- (void)weiBtnClick:(UIButton *)sender{
    VKVoucherChildModel *model = self.dataArray[sender.tag - 10000];
    sender.selected = !sender.selected;
    if (sender.selected) {
        model.isSelectRow = YES;
    }else{
        model.isSelectRow = NO;
    }
    [self.dataArray replaceObjectAtIndex:sender.tag - 10000 withObject:model];
//    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:(UITableViewRowAnimationNone)];
    [self.tableView reloadData];
}
#warning TODO - 我还没有试弟弟
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    VKVoucherChildModel *model = self.dataArray[indexPath.row];
//    VKVoucherChildWeiCell *cell = [VKVoucherChildWeiCell cellWithTableView:tableView withIndexPath:indexPath withModel:self.dataArray[indexPath.row]];
//    cell.deleteBtn.selected = !cell.deleteBtn.selected;
//    if (cell.deleteBtn.selected) {
//        model.isSelectRow = YES;
//    }else{
//        model.isSelectRow = NO;
//    }
//    [self.dataArray replaceObjectAtIndex:indexPath.row withObject:model];
//    //    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:(UITableViewRowAnimationNone)];
//    [self.tableView reloadData];
    
    if (self.yincang == 0) {
        VKVoucherChildModel *model = self.dataArray[indexPath.row];
        model.isSelectRow = !model.isSelectRow;
        [self.tableView reloadData];
    }
}


@end
